package com.skt.common_hr.approval.view
{
	import com.skt.common_hr.approval.events.ApprovalCommandEvent;
	import com.skt.common_hr.approval.model.ApprovalDetailProxy;
	import com.skt.common_hr.approval.model.ToApprovalProxy;
	import com.skt.common_hr.approval.model.vo.ApprovalLineVO;
	import com.skt.common_hr.approval.model.vo.FileVO;
	import com.skt.common_hr.approval.view.components.ApprovalView;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.memberselector.MemberSelectorMediator;
	import com.skt.common_hr.common.puremvc.CommonMediator;
	import com.wcl.utils.StringUtil;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.external.ExternalInterface;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	
	import mx.collections.ArrayCollection;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;

	public class ApprovalViewMediator extends CommonMediator
	{
		public static const NAME:String = "ApprovalViewMediator";
		public static const CLOSED_APPROVAL_VIEW:String = "closedApprovalView";
		public static const CANCEL_APPROVAL_VIEW:String = "cancelApprovalView";
		
		private var selKey:String;
		private var PROCGBN:String;
		private var bWaitingDelegator:Boolean = false;
		private var delegator:String;
		
		private var fileRef:FileReference;
		
			
		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
		public function ApprovalViewMediator()
        {
            super( NAME, null );
        }
		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
		override protected function initializeView():void 
 		{
 			setEventListener();
 		}

		private function setEventListener():void
		{
			view.addEventListener(ApprovalView.CLOSE_VIEW, onCloseView);
			view.addEventListener(ApprovalCommandEvent.EXEC_COMMAND, onCommand);
			view.addEventListener(ApprovalView.DOWNLOAD_ATTACHED_FILE, onClickFile);


 			fileRef = new FileReference();
            //fileRef.addEventListener(IOErrorEvent.IO_ERROR, doEvent);
		}




		public function execView(parent:DisplayObject, key:String, sEacc:String=''):void
		{
			//reqProxy = proxy;
           // registerProxies();
           trace("execView: " + key);
           selKey = key;
			loadApprovalDetail(key);
			if(view==null) {
				createPopUp(parent.root);
			}	
			else {
				PopUpManager.addPopUp(view, parent.root, true);
			}		
			view.setFocus();
			view.htmlArea.visible = true;
			view.buttonBox.selectedIndex = 2;
			view.eaccMode = sEacc;
			view.eaccKey = key;
						
			bActivated = true;
			setEventListener();
			//view.approvalTitle = reqProxy.title;
			//view.content = reqProxy.content;
			//view.htmlArea.visible = true;
			//setApprovalLines();
		}
		
		public function execApproval(parent:DisplayObject, key:String, sEacc:String=''):void
		{
           trace("execApproval: " + key);
           selKey = key;
			loadApprovalDetail(key);
			if(view==null) {
				createPopUp(parent.root);
			}	
			else {
				PopUpManager.addPopUp(view, parent.root, true);
			}		
			view.setFocus();
			view.htmlArea.visible = true;
			view.buttonBox.selectedIndex = 1;
			view.eaccMode = sEacc;
			view.eaccKey = key;			
			bActivated = true;
			setEventListener();
			//view.approvalTitle = reqProxy.title;
			//view.content = reqProxy.content;
			//view.htmlArea.visible = true;
			//setApprovalLines();
		}
		
		private function loadApprovalDetail(key:String):void
		{
			var proxy:ApprovalDetailProxy = facade.retrieveProxy(ApprovalDetailProxy.NAME) as ApprovalDetailProxy;
			proxy.loadDetail(key);
		}


		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array 
		{
			return [
					ApprovalDetailProxy.LOAD_APPROVAL_DETAIL_COMPLETE,
					ApprovalDetailProxy.LOAD_APPROVAL_DETAIL_FAILED,
					ToApprovalProxy.EXEC_ACCEPT_COMPLETE,
					ToApprovalProxy.EXEC_ACCEPT_FAILED,
					ToApprovalProxy.EXEC_REJECT_COMPLETE,
					ToApprovalProxy.EXEC_REJECT_FAILED,
					ToApprovalProxy.EXEC_DELEGATION_COMPLETE,
					ToApprovalProxy.EXEC_DELEGATION_FAILED,
					MemberSelectorMediator.SELECTED_MEMBER,
					MemberSelectorMediator.CANCEL_SELECTION
					];
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			switch(note.getName()) 
			{
				case ApprovalDetailProxy.LOAD_APPROVAL_DETAIL_COMPLETE:
					trace( "ApprovalDetailProxy.LOAD_APPROVAL_DETAIL_COMPLETE" );
					displayDetailView(ApprovalDetailProxy(note.getBody()));
					break;
				case ApprovalDetailProxy.LOAD_APPROVAL_DETAIL_FAILED:
					trace( "ApprovalDetailProxy.LOAD_APPROVAL_DETAIL_FAILED" );
					break;
				case ToApprovalProxy.EXEC_ACCEPT_COMPLETE:
				case ToApprovalProxy.EXEC_REJECT_COMPLETE: 
					view.closeView();
					bActivated = false;
					facade.sendNotification(CLOSED_APPROVAL_VIEW, this);
					break;
				case ToApprovalProxy.EXEC_ACCEPT_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, "ALERT_ERROR_ACCEPT");
					break;
				case ToApprovalProxy.EXEC_REJECT_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, "ALERT_ERROR_REJECT");
					break;
				// 구성원 선택  대화상자에서 구성원 선택
				case MemberSelectorMediator.SELECTED_MEMBER:
					if(bActivated) {
						if(bWaitingDelegator) {
							execDelegation(MemberSelectorMediator(note.getBody()).selectedMember.PERNR);
						}
						else {
							bWaitingDelegator = false;
							view.htmlArea.visible = true;
						}
					}
					break;
				// 구성원 선택  대화상자에서 구성원 취소
				case MemberSelectorMediator.CANCEL_SELECTION:
					if(bActivated) {
						bWaitingDelegator = false;
						view.htmlArea.visible = true;
					}
					break;
				case ToApprovalProxy.EXEC_DELEGATION_COMPLETE:
					view.closeView();
					bActivated = false;
					facade.sendNotification(CLOSED_APPROVAL_VIEW, this);
					break;
				case ToApprovalProxy.EXEC_DELEGATION_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, "위임 저장중 오류가 발생했습니다.",null, "TITLE_DEFAULT", view, viewContent);
					break;
				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}



		private function displayDetailView(proxy:ApprovalDetailProxy):void
		{
			PROCGBN = proxy.detailInfo.PROCGBN;
			view.approvalTitle = proxy.detailInfo.TITLE;
			view.content = proxy.detailInfo.CONTENT;
			if(proxy.fileList.length>0) {
				view.fileInfo = proxy.fileList.getItemAt(0) as FileVO;
			}
			else {
				view.fileInfo = new FileVO();
			}
			view.comment = proxy.detailInfo.CMTXT;
			setApprovalLines(proxy.lineList);
		}

		private function setApprovalLines(src:ArrayCollection):void
		{
			clearAppLine();
			for each(var line:ApprovalLineVO in src)
			{
				setAppLine(line);
			} 
			
		}
		
		private function clearAppLine():void
		{
			view.myInfo = new ApprovalLineVO();
			view.reviewer1 = new ApprovalLineVO();
			view.reviewer2 = new ApprovalLineVO();
			view.reviewer3 = new ApprovalLineVO();
			view.responsible = new ApprovalLineVO();
		}
		
		private function setAppLine(line:ApprovalLineVO):void
		{
			switch(line.GWARELEV) {
				case "01":
					view.myInfo = line;
					break;
				case "02":
					view.reviewer1 = line;
					break;
				case "03":
					view.reviewer2 = line;
					break;
				case "04":
					view.reviewer3 = line;
					break;
				case "09":
					view.responsible = line;
					break;
			}
		}
		private function createPopUp(parent:DisplayObject):void
		{
			viewComponent = PopUpManager.createPopUp(parent, ApprovalView, true);
			PopUpManager.centerPopUp(view);
			view.setFocus();
		}
		
		private function onCommand(e:ApprovalCommandEvent):void
		{
			switch(e.command)
			{
				case 'accept':
					view.htmlArea.visible = false;
					CommonAlert.showMsgYesNo(commonFacade.bundle, "ALERT_COMFIRM_ACCEPT", null, "TITLE_DEFAULT", view,
											yesAccept, noAccept);
					break;
				case 'reject':
					view.htmlArea.visible = false;
					if(StringUtil.NVL(view.txtComment.text)!= "") {
						CommonAlert.showMsgYesNo(commonFacade.bundle, "ALERT_CONFIRM_REJECT", null, "TITLE_DEFAULT", view,
												yesReject, noReject);
					}
					else {
						CommonAlert.showMessage(commonFacade.bundle, "반려시에는 의견을 반드시 입력하셔야 합니다.",null, "TITLE_DEFAULT", view, viewContent);
						view.txtComment.setFocus();
					}
					break;
				case 'delegation':
					view.htmlArea.visible = false;
					selectDelegator();
					break;
				case "print":
					printApproval();
					break;
			}
		}
		
		private function viewContent():void
		{
			view.htmlArea.visible = true;
			view.txtComment.setFocus();
		}
		private function execDelegation(pernr:String):void
		{
			delegator = pernr;
			CommonAlert.showMsgYesNo(commonFacade.bundle, "ALERT_CONFIRM_DELEGATE", null, "TITLE_DEFAULT", view,
									yesDelegation, noprocess);
		}

		private function selectDelegator():void
		{
			var memberSelector:MemberSelectorMediator = 
					facade.retrieveMediator(MemberSelectorMediator.NAME) as MemberSelectorMediator;
			if(memberSelector==null) {
				memberSelector = new MemberSelectorMediator();
				facade.registerMediator(memberSelector);
			}
			memberSelector.exec(view);
			bWaitingDelegator = true;
			/*
			
			*/
		}		
		
		private function printApproval():void
		{
			var CrPattern1:RegExp = /\r/g;
			var CrPattern2:RegExp = /\r\n/g;
			var CrPattern3:RegExp = /\x22/g; 

			var param:Object = new Object;
			param["AppLine"] = new Object;
			param["AppLine"].writer = view.myInfo.ENAME;
			param["AppLine"].reviewer1 = view.reviewer1.ENAME;
			param["AppLine"].reviewer2 = view.reviewer2.ENAME;
			param["AppLine"].reviewer3 = view.reviewer3.ENAME;
			param["AppLine"].responsible = view.responsible.ENAME;
			param["AppDate"] = new Object;
			param["AppDate"].writer = view.myInfo.GWARE_INDATE_F;
			param["AppDate"].reviewer1 = view.reviewer1.GWARE_INDATE_F +"<br>"+StringUtil.NVL(view.reviewer1.WSTATUS_TX);
			param["AppDate"].reviewer2 = view.reviewer2.GWARE_INDATE_F +"<br>"+StringUtil.NVL(view.reviewer2.WSTATUS_TX);
			param["AppDate"].reviewer3 = view.reviewer3.GWARE_INDATE_F +"<br>"+StringUtil.NVL(view.reviewer3.WSTATUS_TX);
			param["AppDate"].responsible = view.responsible.GWARE_INDATE_F +"<br>"+StringUtil.NVL(view.responsible.WSTATUS_TX);
			param["title"] = view.approvalTitle;
			
			var content:String = view.content.replace(CrPattern2, " ");
			content = content.replace(CrPattern1, "<br>");
			content = content.replace(CrPattern3, "˝");
			ExternalInterface.call("execPopUpWindow", content, param);
		}
		
		private function onCloseView(e:Event):void
		{
			view.closeView();
			bActivated = false;
			facade.sendNotification(CANCEL_APPROVAL_VIEW, this);
		}
		
		
		private function yesAccept():void
		{
			var proxy:ToApprovalProxy = facade.retrieveProxy(ToApprovalProxy.NAME) as ToApprovalProxy;
			proxy.acceptApproval(view.txtComment.text, [{GWAREKEY:selKey, PROCGBN:PROCGBN}]);
		}
		
		private function noAccept():void
		{
			view.htmlArea.visible = true;
		}
		private function yesReject():void
		{
			var proxy:ToApprovalProxy = facade.retrieveProxy(ToApprovalProxy.NAME) as ToApprovalProxy;
			proxy.rejectApproval(view.txtComment.text, [{GWAREKEY:selKey, PROCGBN:PROCGBN}]);
		}
		
		private function noReject():void
		{
			view.htmlArea.visible = true;
		}
		
		private function yesDelegation():void
		{
			var proxy:ToApprovalProxy = facade.retrieveProxy(ToApprovalProxy.NAME) as ToApprovalProxy;
			proxy.delegateApproval(delegator, [{GWAREKEY:selKey, PROCGBN:PROCGBN}]);
			bWaitingDelegator = false;
			view.htmlArea.visible = true;
		}
		
		private function noprocess():void
		{
			view.htmlArea.visible = true;
		}
		
		private function onClickFile(e:Event):void
		{
        	var root:String = "/common_infra/";
			var urlReq:URLRequest = new URLRequest(root+view.fileInfo.FILE_URL+"/"+view.fileInfo.FILE_NAME);
			navigateToURL(urlReq, "_blank");
		}
				 
            private function doEvent(evt:Event):void {
                /* Create shortcut to the FileReference object. */
                var fr:FileReference = evt.currentTarget as FileReference;   
				/*
                // Add event order and type to the DataGrid control. 
                arrColl.addItem({data:arrColl.length+1, type:evt.type, eventString:evt.toString()});   

                try {
                    // Update the Model. 
                    fileRefModel.creationDate = fr.creationDate;
                    fileRefModel.creator = fr.creator;
                    fileRefModel.modificationDate = fr.modificationDate;
                    fileRefModel.name = fr.name;
                    fileRefModel.size = fr.size;
                    fileRefModel.type = fr.type;
                    //Display the Text control. 
                    txt.visible = true;
                } catch (err:*) {
                    // uh oh, an error of sorts. 
                }
                */
            }   
			
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():ApprovalView
        {
            return viewComponent as ApprovalView;
        }
	}
}